package com.qlylkj.lbk.model.repository


import com.qlylkj.lbk.model.api.BaseRepository
import com.qlylkj.lbk.model.api.ResultResponse
import com.qlylkj.lbk.model.api.RetrofitHelper
import com.qlylkj.lbk.model.api.WeChatApi
import com.qlylkj.lbk.wxapi.WXUserInfo
import com.qlylkj.lbk.wxapi.WXAccessTokenInfo
import com.qlylkj.lbk.wxapi.WeChatConstant
import java.io.IOException

/**
 *    author : duanguosen
 *    date   : 2019/11/27
 *    desc   :
 */
class WeChatRepository: BaseRepository() {

    private val weChatApi by lazy { RetrofitHelper.getService(WeChatApi::class.java) }

    private fun validateSuccess(wxAccessTokenInfo: WXAccessTokenInfo): Boolean {
        return (wxAccessTokenInfo.errcode.isNullOrEmpty() || "0" == wxAccessTokenInfo.errcode)
    }

    private fun validateSuccess(wxUserInfo: WXUserInfo): Boolean {
        return (wxUserInfo.errcode.isNullOrEmpty() || "0" == wxUserInfo.errcode)
    }


    private fun requestBodyGetAccessToken(authRespCode: String): MutableMap<String, Any> {
        val map = mutableMapOf<String, Any>()
        map[WeChatConstant.APP_ID_KEY] = WeChatConstant.APP_ID
        map[WeChatConstant.APP_SECRET_KEY] = WeChatConstant.APP_SECRET
        map[WeChatConstant.APP_CODE_KEY] = authRespCode
        map[WeChatConstant.GRANT_TYPE_KEY] = WeChatConstant.AUTHORIZATION_CODE
        return map
    }

    private fun requestBodyGetWXUserInfo(accessToken: String, openid: String): MutableMap<String, Any> {
        val map = mutableMapOf<String, Any>()
        map[WeChatConstant.ACCESS_TOKEN_KEY] = accessToken
        map[WeChatConstant.OPENID_KEY] = openid
        return map
    }

    suspend fun getAccessToken(authRespCode: String): ResultResponse<WXUserInfo> {
        return safeApiCallEntity(
            call = { requestGetAccessToken(authRespCode) },
            errorMessage = "拒绝授权"
        )
    }

    private suspend fun requestGetAccessToken(authRespCode: String): ResultResponse<WXUserInfo> {
        val response = weChatApi.getAccessTokenAsync(requestBodyGetAccessToken(authRespCode))
        return if (validateSuccess(response)) {
            getWXUserInfo(response.access_token,response.openid)
        }else{
            ResultResponse.Error(IOException("拒绝授权"))
        }
    }

    private suspend fun getWXUserInfo(accessToken: String, openid: String): ResultResponse<WXUserInfo> {
        return safeApiCallEntity(
            call = { requestGetWXUserInfo(accessToken,openid) },
            errorMessage = "获取微信用户个人资料失败"
        )
    }

    private suspend fun requestGetWXUserInfo(accessToken: String, openid: String): ResultResponse<WXUserInfo> {
        val response = weChatApi.getWXUserInfoAsync(requestBodyGetWXUserInfo(accessToken,openid))
        return if (validateSuccess(response)) {
            ResultResponse.SuccessEntity(response)
        }else{
            ResultResponse.Error(IOException("获取微信用户个人资料失败"))
        }
    }

}